package com.tianhui.consignortwofei.mvp.ui.fragment;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentActivity;

import com.fgs.common.CommonModel;
import com.fgs.common.CommonResponse;
import com.fgs.common.api.CommonConfig;
import com.fgs.common.other.CommonEvent;
import com.fgs.common.permission.OnPermissionCheckResult;
import com.fgs.common.permission.PermissionHelper;
import com.fgs.common.progress.ExceptionHandle;
import com.fgs.common.progress.ObserverResponseListener;
import com.fgs.common.utils.ToastUtil;
import com.fgs.common.widget.dialog.OperateTipDialog;
import com.tianhui.consignortwofei.R;
import com.tianhui.consignortwofei.api.OrderApiService;
import com.tianhui.consignortwofei.constant.KeyValue;
import com.tianhui.consignortwofei.constant.OrderType;
import com.tianhui.consignortwofei.manager.EventBusManage;
import com.tianhui.consignortwofei.mvp.contract.OrderListContract;
import com.tianhui.consignortwofei.mvp.model.enty.OrderCondition;
import com.tianhui.consignortwofei.mvp.model.enty.OrderInfo;
import com.tianhui.consignortwofei.mvp.model.enty.OrderOperateInfo;
import com.tianhui.consignortwofei.mvp.presenter.OrderListPresenter;
import com.tianhui.consignortwofei.mvp.ui.activity.DriverFeedBackActivity;
import com.tianhui.consignortwofei.mvp.ui.activity.EvaluationActivity;
import com.tianhui.consignortwofei.mvp.ui.activity.HeDanDetailActivity;
import com.tianhui.consignortwofei.mvp.ui.activity.OrderDetailActivity;
import com.tianhui.consignortwofei.mvp.ui.activity.OrderOperateActivity;
import com.tianhui.consignortwofei.mvp.ui.activity.VehicleTrajectoryActivity;
import com.tianhui.consignortwofei.mvp.ui.adapter.InTransitListAdapter;
import com.tianhui.consignortwofei.other.EventWhat;
import com.tianhui.consignortwofei.pattern.orderOprate.impl.DeliveryConfirmOperate;
import com.tianhui.consignortwofei.pattern.orderOprate.impl.LoadingConfirmOperate;
import com.tianhui.consignortwofei.pattern.orderOprate.impl.TerminateDispatchOperate;
import com.tianhui.consignortwofei.pattern.orderOprate.impl.VehicleTrajectoryOperate;
import com.tianhui.consignortwofei.pattern.orderStatus.status.IOrderStatus;
import com.tianhui.consignortwofei.widget.QRCodeDialog;
import com.xuexiang.xaop.annotation.IOThread;
import com.xuexiang.xaop.enums.ThreadType;
import com.xuexiang.xqrcode.XQRCode;
import com.xuexiang.xutil.app.IntentUtils;
import com.xuexiang.xutil.display.ImageUtils;
import com.xuexiang.xutil.security.Base64Utils;

import org.yczbj.ycrefreshviewlib.adapter.RecyclerArrayAdapter;
import org.yczbj.ycrefreshviewlib.inter.OnItemChildClickListener;
import org.yczbj.ycrefreshviewlib.inter.OnItemClickListener;

import java.util.HashMap;
import java.util.Map;

/**
 * @author fgs
 * @date 2020/8/27
 * @description
 **/
public class InTransitListFragment extends SearchFragment<OrderListContract.View, OrderListContract.Presenter> implements OrderListContract.View {

    private boolean isNeedLazyLoad = true;
    private IOrderStatus mIOrderStatus;
    private String mSearchKey;

    public InTransitListFragment() {
        // Required empty public constructor
    }

    @Override
    public boolean isNeedLazyLoad() {
        return this.isNeedLazyLoad;
    }

    public static InTransitListFragment newInstance(IOrderStatus iOrderStatus) {
        InTransitListFragment orderListFragment = new InTransitListFragment();
        orderListFragment.setOrderStatus(iOrderStatus);
        return orderListFragment;
    }

    private InTransitListFragment setOrderStatus(IOrderStatus iOrderStatus) {
        mIOrderStatus = iOrderStatus;
        return this;
    }

    public InTransitListFragment setIsNeedLazyLoad(boolean isNeedLazyLoad) {
        this.isNeedLazyLoad = isNeedLazyLoad;
        return this;
    }

    public InTransitListFragment setSearchKey(String searchKey) {
        mSearchKey = searchKey;
        return this;
    }


    @Override
    protected OrderListContract.View createView() {
        return this;
    }

    @Override
    protected OrderListContract.Presenter createPresenter() {
        return new OrderListPresenter(getContext());
    }


    @Override
    public RecyclerArrayAdapter createAdapter() {
        return new InTransitListAdapter(getContext(), mIOrderStatus);
    }

    @Override
    protected void initListener() {

        mAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                Object object = mAdapter.getAllData().get(position);
                if (object instanceof OrderInfo) {
                    OrderInfo orderInfo = (OrderInfo) object;
                    Bundle bundle = new Bundle();
                    bundle.putParcelable(KeyValue.KEY_ORDER_INFO, orderInfo);
                    bundle.putInt(KeyValue.KEY_TYPE, mIOrderStatus.getOrderStatusType());

                    if (mIOrderStatus.getOrderStatusType() != OrderType.TYPE_PAYMENT) {
                        openActivity(OrderDetailActivity.class, bundle);
                    }
                }

            }
        });

        mAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(View view, int position) {
                Object object = mAdapter.getAllData().get(position);
                OrderInfo orderInfo = null;
                if (object instanceof OrderInfo) {
                    orderInfo = (OrderInfo) object;
                }
                Bundle bundle;
                OrderOperateInfo operateInfo;
                if (orderInfo != null) {
                    switch (view.getId()) {
                        case R.id.iv_phone:
                            if (!TextUtils.isEmpty(orderInfo.drivertel)) {
                                startActivity(IntentUtils.getDialIntent(orderInfo.drivertel));
                            } else {
                                ToastUtil.showShortToast("未识别到司机电话");
                            }

                            break;
                        case R.id.ll_driver_line_body:


                            operateInfo = new OrderOperateInfo();
                            operateInfo.operate = "车辆轨迹";
                            operateInfo.orderInfo = orderInfo;
                            operateInfo.iOrderOperate = new VehicleTrajectoryOperate();
                            if (operateInfo.orderInfo != null) {
                                if (operateInfo.orderInfo.isstate == 7 || operateInfo.orderInfo.isstate == 9 || operateInfo.orderInfo.isstate > 11) {
                                    Intent intent = new Intent(getContext(), VehicleTrajectoryActivity.class);
                                    bundle = new Bundle();
                                    bundle.putParcelable(KeyValue.KEY_ORDER_INFO, operateInfo.orderInfo);
                                    intent.putExtras(bundle);
                                    startActivity(intent);
                                } else {
                                    ToastUtil.showShortToast("该订单无车辆轨迹信息");
                                }
                            } else {
                                ToastUtil.showShortToast("获取订单信息失败");
                            }

                            break;


                        case R.id.tv_guanli:
                            if (mIOrderStatus != null) {
                                bundle = new Bundle();
                                bundle.putInt(KeyValue.KEY_TYPE, mIOrderStatus.getOrderStatusType());
                                bundle.putParcelable(KeyValue.KEY_ORDER_INFO, orderInfo);
                                openActivity(OrderOperateActivity.class, bundle);
                            }

                            break;
                        case R.id.tv_cancel:


                            operateInfo = new OrderOperateInfo();
                            operateInfo.operate = "终止单据";
                            operateInfo.orderInfo = orderInfo;
                            operateInfo.iOrderOperate = new TerminateDispatchOperate();
                            operateInfo.iOrderOperate.orderOperate(getContext(), operateInfo);


                            break;

                        case R.id.tv_true_shou:

                            operateInfo = new OrderOperateInfo();
                            operateInfo.operate = "确认收货";
                            operateInfo.orderInfo = orderInfo;
                            operateInfo.isEnable = orderInfo.isrecelve == 0;
                            operateInfo.iOrderOperate = new DeliveryConfirmOperate();
                            operateInfo.iOrderOperate.orderOperate(getContext(), operateInfo);

                            break;
                        case R.id.tv_true_zhuang:

                            operateInfo = new OrderOperateInfo();
                            operateInfo.operate = "确认装车";
                            operateInfo.orderInfo = orderInfo;
                            operateInfo.isEnable = orderInfo.istrans == 0;
                            operateInfo.iOrderOperate = new LoadingConfirmOperate();
                            operateInfo.iOrderOperate.orderOperate(getContext(), operateInfo);
                            break;
                        case R.id.tv_change_price://调整价格
                            showTerminateDialog(orderInfo);

                            break;
                        case R.id.tv_change_weight://调整重量
                            showWeightDialog(orderInfo);

                            break;
                        case R.id.tv_change_hedan:

                            operateInfo = new OrderOperateInfo();
                            operateInfo.operate = "合单";
                            operateInfo.orderInfo = orderInfo;
                            operateInfo.isEnable = orderInfo.istrans == 0;
                            operateInfo.iOrderOperate = new LoadingConfirmOperate();
//                            operateInfo.iOrderOperate.orderOperate(getContext(), operateInfo);

                            bundle = new Bundle();
                            bundle.putParcelable(KeyValue.KEY_ORDER_INFO, operateInfo.orderInfo);
                            bundle.putInt(KeyValue.KEY_TYPE, OrderType.TYPE_HE_DAN);
                            Intent intent = new Intent(getContext(), HeDanDetailActivity.class);
                            intent.putExtras(bundle);
                            getContext().startActivity(intent);
                            break;

                            //评价
                        case R.id.tv_true_pingjia:
                            if (mIOrderStatus != null) {
                                bundle = new Bundle();
                                bundle.putInt(KeyValue.KEY_TYPE, mIOrderStatus.getOrderStatusType());
                                bundle.putParcelable(KeyValue.KEY_ORDER_INFO, orderInfo);
                                openActivity(EvaluationActivity.class, bundle);
                            }

                            break;
                        //投诉
                        case R.id.tv_true_tousu:
                            if (mIOrderStatus != null) {
                                bundle = new Bundle();
                                bundle.putInt(KeyValue.KEY_TYPE, mIOrderStatus.getOrderStatusType());
                                bundle.putParcelable(KeyValue.KEY_ORDER_INFO, orderInfo);
                                openActivity(DriverFeedBackActivity.class, bundle);
                            }

                            break;


//                    case R.id.item_order_list_submitTextView:
//                        if (orderInfo != null) {
//                            Bundle bundle = new Bundle();
//                            bundle.putParcelable(KeyValue.KEY_ORDER_INFO, orderInfo);
//                            bundle.putInt(KeyValue.KEY_TYPE, mIOrderStatus.getOrderStatusType());
//                            openActivity(OrderDetailActivity.class, bundle);
//                        }
//
//                        break;
//                    case R.id.item_order_list_shareOrderCodeTextView:
//                        if (orderInfo != null) {
//                            showShareCode(orderInfo);
//                        }
//                        break;
//                    case R.id.item_order_list_editOrderTextView:
//                        if (orderInfo != null) {
//                            Bundle bundle = new Bundle();
//                            bundle.putString(KeyValue.KEY_ID, orderInfo.id);
//                            openActivity(EditDeliveryGoodsStepOneActivity.class, bundle);
//                        }
//                        break;
//                    case R.id.tv_tonghua:
//                        if (orderInfo != null) {
//                            Bundle bundle = new Bundle();
//                            bundle.putString("sourcenum", orderInfo.billno);
//                            openActivity(TongHuaLogActivity.class, bundle);
//                        }
////                        Toast.makeText(getContext(), "通话记录", Toast.LENGTH_SHORT).show();
//                        break;
//                    case R.id.tv_liulan:
//                        if (orderInfo != null) {
//                            Bundle bundle = new Bundle();
//                            bundle.putString("sourcenum", orderInfo.billno);
//                            openActivity(LiuLanLogActivity.class, bundle);
//                        }
//                        Toast.makeText(getContext(), "浏览记录", Toast.LENGTH_SHORT).show();
//                        break;
                    }
                }else {
                    ToastUtil.showShortToast("数据获取错误");
                }
            }
        });

    }

    private void showShareCode(OrderInfo orderInfo) {
        new PermissionHelper().checkPermissions((FragmentActivity) getContext(), new OnPermissionCheckResult() {
            @Override
            public void grantedResult() {

                if (!TextUtils.isEmpty(orderInfo.billno)) {
                    String base64BillNo = Base64Utils.encode(orderInfo.billno);
                    Bitmap bitmap = createQRCodeWithLogo(base64BillNo, ImageUtils.getBitmap(R.mipmap.icon_app));
                    new QRCodeDialog(getContext(), bitmap).show();
                } else {
                    showToast("获取订单信息失败");
                }

            }

            @Override
            public void shouldShowRequestPermissionRationale() {

            }

            @Override
            public void grantedForbidResult() {

            }
        }, Manifest.permission.WRITE_EXTERNAL_STORAGE);
    }

    /**
     * 生成简单的带logo的二维码
     *
     * @param content
     * @param logo
     */
    @IOThread(ThreadType.Single)
    private Bitmap createQRCodeWithLogo(String content, Bitmap logo) {
        Bitmap bitmap = XQRCode.createQRCodeWithLogo(content, 400, 400, logo);
        return bitmap;
    }

    @Override
    public void requestDataList(int page, boolean isDialog) {
        if (mIOrderStatus != null) {
            OrderCondition orderCondition = new OrderCondition();
            orderCondition.page = page;
            orderCondition.searchKey = mSearchKey;
            getPresenter().requestOrderList(mIOrderStatus.getOrderListObservable(orderCondition), isDialog);
        }
    }

    @Override
    public void initData() {

        if (mIOrderStatus != null) {
            setSearchKeyHint(mIOrderStatus.getSearchHint());
        }



    }

    @Override
    protected void requestSearch(String searchKey) {
        mSearchKey = searchKey;
        refreshData(true);
    }

    @Override
    protected void changeSearchKey(String searchKey) {
        mSearchKey = searchKey;
    }

    @Override
    public void onEvent(CommonEvent event) {
        super.onEvent(event);
        switch (EventWhat.valueOf(event.getWhat())) {
            case EVENT_REFRESH_ORDER_LIST:
                if (isHasLoadData())
                    refreshData(false);
                break;
        }
    }



    private void showTerminateDialog(OrderInfo orderInfo) {
        new OperateTipDialog.Builder(getActivity())
                .title("原来的价格为："+orderInfo.tradprice+"元")
                .input(new OperateTipDialog.InputCallback() {
                    @Override
                    public void onInput(@NonNull OperateTipDialog dialog, CharSequence input) {
                    }
                })
                .positiveText("确定")
                .negativeText("取消")
                .onPositive(new OperateTipDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull OperateTipDialog dialog) {
                        String reason = dialog.getInputContent();
                        if (TextUtils.isEmpty(reason)) {
                            ToastUtil.showShortToast("请输入要修改的价格");
                            return;
                        }
                        dialog.dismiss();

                        changeYunShuPrice(orderInfo.dispatchno,reason);
                    }
                })
                .show();
    }

    private void changeYunShuPrice(String dispatchno,String price) {

        Map<String, String> map = new HashMap<>();
        map.put("billno", dispatchno);
        map.put("price", price);
        new CommonModel().subscribe(getActivity(), CommonConfig.getInstance().create(OrderApiService.class).changePriceYunShu(map), new ObserverResponseListener<CommonResponse>() {
            @Override
            public void onNext(CommonResponse commonResponse) {
                if (commonResponse.getCode() == 20000) {

//                    EventBusManage.operateActivityFinish();
//                    EventBusManage.refreshOrderDetail();
                    EventBusManage.refreshOrderList();
                    ToastUtil.showShortToast("调整成功");

                } else {
                    ToastUtil.showShortToast(commonResponse.getMsg());
                }

            }

            @Override
            public void onError(ExceptionHandle.ResponseThrowable e) {
                ToastUtil.showShortToast(e.message);
            }
        });
    }



    private void showWeightDialog(OrderInfo orderInfo) {
        new OperateTipDialog.Builder(getActivity())
                .title("原来的重量为："+orderInfo.tradweight+"吨")
                .input(new OperateTipDialog.InputCallback() {
                    @Override
                    public void onInput(@NonNull OperateTipDialog dialog, CharSequence input) {
                    }
                })
                .positiveText("确定")
                .negativeText("取消")
                .onPositive(new OperateTipDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull OperateTipDialog dialog) {
                        String reason = dialog.getInputContent();
                        if (TextUtils.isEmpty(reason)) {
                            ToastUtil.showShortToast("请输入要修改的重量");
                            return;
                        }
                        dialog.dismiss();

                        changeYunShuWeight(orderInfo.dispatchno,reason);
                    }
                })
                .show();
    }

    private void changeYunShuWeight(String dispatchno,String weight) {

        Map<String, String> map = new HashMap<>();
        map.put("billno", dispatchno);
        map.put("weight", weight);
        new CommonModel().subscribe(getActivity(), CommonConfig.getInstance().create(OrderApiService.class).changePriceYunShu(map), new ObserverResponseListener<CommonResponse>() {
            @Override
            public void onNext(CommonResponse commonResponse) {
                if (commonResponse.getCode() == 20000) {

//                    EventBusManage.operateActivityFinish();
//                    EventBusManage.refreshOrderDetail();
                    EventBusManage.refreshOrderList();
                    ToastUtil.showShortToast("调整成功");

                } else {
                    ToastUtil.showShortToast(commonResponse.getMsg());
                }

            }

            @Override
            public void onError(ExceptionHandle.ResponseThrowable e) {
                ToastUtil.showShortToast(e.message);
            }
        });
    }


















}
